import { WebSocketServer } from "ws";
import Mock from "mockjs";

const wss = new WebSocketServer({ port: 9988 });

/*
  需求：每隔一段时间给客户端发送数据
*/
let id = 1;

function getData() {
  let { list } = Mock.mock({
    "list|1-10": [
      {
        date: "@date",
        address: "@city",
        num: "@integer(100, 10000)",
      },
    ],
  });

  list = list.map((item) => {
    return {
      ...item,
      id: id++,
    };
  });

  return list;
}

wss.on("connection", function connection(socket) {
  // 向客户端发送列表数据消息
  sendListMessage(socket);
  
  // 绑定客户端断开连接的监听
  socket.onclose = () => {
    console.log('关闭连接')
    clearInterval(socket.timer)
    socket.removeListener('message', handleMessage)
  }

  const handleMessage = (data) => {
    // 如果接收到ping的消息, 发客户端发送pong的消息
    if (data.toString() === "ping") {
      console.log("接受心跳ping消息");
      socket.send("pong");
    }
  }

  // 绑定接收客户端消息的监听
  socket.on("message", handleMessage);
});

// 每隔1-9秒向客户端发送一个列表数据
function sendListMessage(socket) {
  console.log('准备发送列表数据')
  const time = Math.floor(Math.random()*8000 + 2000)
  socket.timer = setInterval(() => {
    // 得到新的随机数据
    const data = getData()
    // 发送给浏览器
    socket.send(JSON.stringify(data))
  }, time);
}